<template>
  <div>
    <!-- 主要症状 -->
    <div class="diagnosis-card">
      <div class="card-header">
        <i class="icon-symptom"></i>
        <span class="card-title">主要症状</span>
      </div>
      <div class="card-content">
        <textarea
          v-model="symptoms"
          placeholder="描述患者主要症状..."
          class="symptom-textarea"
          :disabled="isSystemStopped"
          @input="updateProgress"
        ></textarea>
      </div>
    </div>

    <!-- 病情说明 -->
    <div class="diagnosis-card">
      <div class="card-header">
        <i class="icon-description"></i>
        <span class="card-title">病情说明</span>
      </div>
      <div class="card-content">
        <textarea
          v-model="description"
          placeholder="详细说明病情发展、持续时间等..."
          class="description-textarea"
          :disabled="isSystemStopped"
          @input="updateProgress"
        ></textarea>
      </div>
    </div>

    <!-- 康复建议 -->
    <div class="diagnosis-card">
      <div class="card-header">
        <i class="icon-description"></i>
        <span class="card-title">康复建议</span>
        <button class="btn btn-submit mode-switch-btn" @click="toggleMode" :disabled="isSystemStopped">
          {{ selected_mode === 'selection' ? '手写模式' : '选择模式' }}
        </button>
      </div>
      <div class="card-content">
        <!-- 选择模式 -->
        <div class="selection-mode" v-if="selected_mode === 'selection'">
          <div class="suggestion-category">
            <h4><i class="fas fa-utensils"></i> 饮食建议</h4>
            <p @click="toggleAdvice('diet')" :class="{ 'cursor-pointer': !isSystemStopped }">
              {{ currentAdvices.diet }}
              <i class="fas fa-chevron-down" :class="{ 'expanded': dietExpanded }"></i>
            </p>
            <div class="suggestion-options" v-if="dietExpanded">
              <div
                class="option-item"
                v-for="(item, index) in adviceData.diet"
                :key="index"
                @click="selectAdvice('diet', index)"
                :disabled="isSystemStopped"
              >
                {{ item }}
              </div>
            </div>
          </div>

          <div class="suggestion-category">
            <h4><i class="fas fa-running"></i> 运动建议</h4>
            <p @click="toggleAdvice('sports')" :class="{ 'cursor-pointer': !isSystemStopped }">
              {{ currentAdvices.sports }}
              <i class="fas fa-chevron-down" :class="{ 'expanded': sportsExpanded }"></i>
            </p>
            <div class="suggestion-options" v-if="sportsExpanded">
              <div
                class="option-item"
                v-for="(item, index) in adviceData.sports"
                :key="index"
                @click="selectAdvice('sports', index)"
                :disabled="isSystemStopped"
              >
                {{ item }}
              </div>
            </div>
          </div>

          <div class="suggestion-category">
            <h4><i class="fas fa-bed"></i> 睡眠建议</h4>
            <p @click="toggleAdvice('sleep')" :class="{ 'cursor-pointer': !isSystemStopped }">
              {{ currentAdvices.sleep }}
              <i class="fas fa-chevron-down" :class="{ 'expanded': sleepExpanded }"></i>
            </p>
            <div class="suggestion-options" v-if="sleepExpanded">
              <div
                class="option-item"
                v-for="(item, index) in adviceData.sleep"
                :key="index"
                @click="selectAdvice('sleep', index)"
                :disabled="isSystemStopped"
              >
                {{ item }}
              </div>
            </div>
          </div>
        </div>

        <!-- 手写模式 -->
        <div v-else>
          <textarea
            v-model="otherContent"
            placeholder="医生手写康复建议....."
            class="description-textarea"
            :disabled="isSystemStopped"
            @input="updateOther();updateProgress()"
          ></textarea>
        </div>
      </div>
    </div>

    <!-- 诊疗进度 -->
    <div class="progress-card">
      <div class="card-header">
        <i class="icon-progress"></i>
        <span class="card-title">诊疗进度</span>
        <div class="system-status" :class="isSystemStopped ? 'stopped' : 'running'">
          {{ isSystemStopped ? '系统已暂停' : '系统运行中' }}
        </div>
      </div>
      <div class="progress-steps">
        <div v-for="(step, index) in progressSteps" :key="index"
             class="progress-step" :class="{ completed: step.completed }">
          <div class="step-indicator">
            <span class="step-number">{{ index + 1 }}</span>
            <div class="step-check">✓</div>
          </div>
          <span class="step-label">{{ step.label }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

// 1. 完善Props定义：接收父组件传递的adviceData（与父组件保持一致）
const props = defineProps({
  progressSteps: Array,
  isSystemStopped: Boolean,
  symptoms: String,
  description: String,
  adviceData: { // 新增：接收父组件的康复建议数据（覆盖子组件本地默认值）
    type: Object,
    required: false,
    default: () => ({
      diet: ['饮食清淡', '少食多餐', '避免油腻', '多吃蔬果'],
      sports: ['适度运动', '避免久坐', '每日散步', '循序渐进'],
      sleep: ['保持规律作息', '避免熬夜', '睡前放松', '保证时长']
    })
  }
})

const emit = defineEmits(['update:progressSteps', 'update:symptoms', 'update:description', 'update:rehab'])

// 同步父组件状态
const progressSteps = ref([...props.progressSteps])
const symptoms = ref(props.symptoms || '') // 兜底空字符串，避免undefined
const description = ref(props.description || '') // 兜底空字符串

// 康复建议相关状态 - 默认手写模式（保持原有）
const selected_mode = ref('other')
const otherContent = ref('')
const currentAdvices = ref({
  diet: '饮食清淡',
  sports: '适度运动',
  sleep: '保持规律作息'
})
// 改为使用父组件传递的adviceData（优先父组件数据，无则用默认）
const adviceData = ref(props.adviceData)
const dietExpanded = ref(false)
const sportsExpanded = ref(false)
const sleepExpanded = ref(false)

// 2. 监听父组件状态变化（保持原有，补充symptoms/description的本地存储同步）
watch(() => props.progressSteps, (newVal) => {
  progressSteps.value = [...newVal]
}, { deep: true })

watch(() => props.symptoms, (newVal) => {
  symptoms.value = newVal || ''
  localStorage.setItem('symptoms', newVal || '') // 同步到本地存储，供父组件读取
})

watch(() => props.description, (newVal) => {
  description.value = newVal || ''
  localStorage.setItem('description', newVal || '') // 同步到本地存储，供父组件读取
})

// 监听父组件传递的adviceData变化（实时同步）
watch(() => props.adviceData, (newVal) => {
  if (newVal) {
    adviceData.value = newVal
    // 若父组件数据更新，同步当前选中的建议（避免数据不一致）
    currentAdvices.value = {
      diet: newVal.diet[0] || currentAdvices.value.diet,
      sports: newVal.sports[0] || currentAdvices.value.sports,
      sleep: newVal.sleep[0] || currentAdvices.value.sleep
    }
  }
}, { deep: true })

// 3. 更新进度（优化判断逻辑，避免空字符串误判）
const updateProgress = () => {
  // 主要症状进度：去除空格后判断
  progressSteps.value[1].completed = symptoms.value.trim().length > 0
  // 病情说明进度：去除空格后判断
  progressSteps.value[2].completed = description.value.trim().length > 0
  // 康复建议进度：优化判断逻辑
  if (selected_mode.value === 'selection') {
    // 选择模式：确保有有效建议才视为完成
    progressSteps.value[3].completed = !!currentAdvices.value.diet.trim()
  } else {
    // 手写模式：去除空格后判断
    progressSteps.value[3].completed = otherContent.value.trim().length > 0
  }

  // 触发更新：同步父组件状态+本地存储
  emit('update:progressSteps', [...progressSteps.value])
  emit('update:symptoms', symptoms.value)
  emit('update:description', description.value)
  // 同步症状和病情说明到本地存储（供父组件提交时读取）
  localStorage.setItem('symptoms', symptoms.value)
  localStorage.setItem('description', description.value)
}

// 4. 康复建议方法（补充系统暂停判断，避免误操作）
const toggleMode = () => {
  if (props.isSystemStopped) return // 系统暂停时禁止切换
  selected_mode.value = selected_mode.value === 'selection' ? 'other' : 'selection'
  updateProgress()
  const content = selected_mode.value === 'other' ? otherContent.value : currentAdvices.value
  emit('update:rehab', { mode: selected_mode.value, content })
  updateStorage()
}

const toggleAdvice = (type) => {
  if (props.isSystemStopped) return // 系统暂停时禁止展开/收起
  // 优化：展开当前分类时，收起其他分类
  dietExpanded.value = type === 'diet' ? !dietExpanded.value : false
  sportsExpanded.value = type === 'sports' ? !sportsExpanded.value : false
  sleepExpanded.value = type === 'sleep' ? !sleepExpanded.value : false
}

const selectAdvice = (type, index) => {
  if (props.isSystemStopped) return // 系统暂停时禁止选择
  currentAdvices.value[type] = adviceData.value[type][index] || ''
  toggleAdvice(type)
  emit('update:rehab', { mode: selected_mode.value, content: currentAdvices.value })
  updateStorage()
}

// 手写模式输入时同步更新
const updateOther = () => {
   if (props.isSystemStopped) return
    // 显式确保 otherContent 是最新输入值（v-model 已同步，这里是双重保险）
    const latestContent = otherContent.value.trim();
    emit('update:rehab', { mode: selected_mode.value, content: latestContent })
    updateStorage() // 同步到 localStorage
    updateProgress()
}

// 5. 本地存储更新（保持原有，确保与父组件存储键一致）
const updateStorage = () => {
  localStorage.setItem('rehabilitation_mode', selected_mode.value)
  if (selected_mode.value === 'other') {
    localStorage.setItem('other', otherContent.value)
    localStorage.removeItem('diet')
    localStorage.removeItem('sports')
    localStorage.removeItem('sleep')
  } else {
    localStorage.setItem('diet', currentAdvices.value.diet)
    localStorage.setItem('sports', currentAdvices.value.sports)
    localStorage.setItem('sleep', currentAdvices.value.sleep)
    localStorage.removeItem('other')
  }
}

// 6. 组件挂载时初始化（从本地存储恢复状态，确保刷新后数据不丢失）
onMounted(() => {
  // 恢复康复建议模式和内容
  const savedMode = localStorage.getItem('rehabilitation_mode')
  if (savedMode) selected_mode.value = savedMode

  if (selected_mode.value === 'other') {
    const savedOther = localStorage.getItem('other')
    if (savedOther) otherContent.value = savedOther
  } else {
    const savedDiet = localStorage.getItem('diet')
    const savedSports = localStorage.getItem('sports')
    const savedSleep = localStorage.getItem('sleep')
    if (savedDiet) currentAdvices.value.diet = savedDiet
    if (savedSports) currentAdvices.value.sports = savedSports
    if (savedSleep) currentAdvices.value.sleep = savedSleep
  }

  // 恢复症状和病情说明（从本地存储读取，优先级高于父组件初始值）
  const savedSymptoms = localStorage.getItem('symptoms')
  const savedDescription = localStorage.getItem('description')
  if (savedSymptoms) {
    symptoms.value = savedSymptoms
    emit('update:symptoms', savedSymptoms) // 同步到父组件
  }
  if (savedDescription) {
    description.value = savedDescription
    emit('update:description', savedDescription) // 同步到父组件
  }

  // 初始化进度
  updateProgress()
})
</script>

<style scoped>
/* 卡片通用样式 */
.diagnosis-card, .progress-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}
.card-header {
  display: flex;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f2f5;
}
.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin-left: 10px;
}
.card-header i {
  font-size: 20px;
  color: #4a6cf7;
}
.card-content {
  padding: 20px 24px;
}

/* 文本域样式 */
.symptom-textarea, .description-textarea {
  width: 100%;
  padding: 16px;
  border: 2px solid #e8eaf0;
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.5;
  resize: vertical;
  transition: all 0.3s;
  background: #fafbfc;
  min-height: 80px;
}
.symptom-textarea:focus:not(:disabled), .description-textarea:focus:not(:disabled) {
  border-color: #4a6cf7;
  background: white;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
  outline: none;
}
.symptom-textarea:disabled, .description-textarea:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 康复建议样式 */
.mode-switch-btn {
  padding: 4px 10px !important;
  font-size: 14px !important;
  margin-left: auto !important;
  width: auto !important;
  height: auto !important;
}
.suggestion-category {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.suggestion-category h4 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}
.suggestion-category p {
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.5;
  margin: 0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.suggestion-options {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #e0e0e0;
}
.option-item {
  padding: 6px 0;
  font-size: 14px;
  color: #34495e;
  cursor: pointer;
  transition: all 0.2s;
}
.option-item:hover {
  background-color: #e9ecef;
  padding-left: 5px;
  border-left: 2px solid #3498db;
}
.fas.fa-chevron-down {
  font-size: 12px;
  color: #7f8c8d;
  transition: transform 0.3s;
}
.fas.fa-chevron-down.expanded {
  transform: rotate(180deg);
}

/* 进度卡片样式 */
.progress-card .card-content {
  padding: 20px 24px;
}
.progress-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-left:14px;
}
.progress-step {
  display: flex;
  align-items: center;
  gap: 16px;
}
.step-indicator {
  position: relative;
  width: 32px;
  height: 32px;
  flex-shrink: 0;
}
.step-number {
  position: absolute;
  top: 0;
  left: 0;
  width: 32px;
  height: 32px;
  background: #f0f2f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  color: #8f9bb3;
  transition: all 0.3s;
}
.step-check {
  position: absolute;
  top: 0;
  left: 0;
  width: 32px;
  height: 32px;
  background: #4a6cf7;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  opacity: 0;
  transform: scale(0.8);
  transition: all 0.3s;
}
.progress-step.completed .step-number {
  opacity: 0;
  transform: scale(0.8);
}
.progress-step.completed .step-check {
  opacity: 1;
  transform: scale(1);
}
.step-label {
  font-weight: 500;
  color: #1a1a1a;
  transition: all 0.3s;
}
.progress-step.completed .step-label {
  color: #4a6cf7;
}

/* 系统状态 */
.system-status {
  margin-left: auto;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}
.system-status.running {
  background: #e7f7ef;
  color: #0ca678;
}
.system-status.stopped {
  background: #ffe3e3;
  color: #fa5252;
}

/* 按钮样式 */
.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 28px;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 140px;
  justify-content: center;
}
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}
.btn-submit {
  background: linear-gradient(135deg, #4a6cf7, #6c8aff);
  color: white;
  border: 2px solid #4a6cf7;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.3);
}
.btn-submit:hover:not(.disabled):not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(74, 108, 247, 0.4);
}

/* 图标样式 */
.icon-symptom::before { content: "📋"; }
.icon-description::before { content: "📝"; }
.icon-progress::before { content: "📊"; }
</style>